﻿using System.Collections.Generic;
using System.Threading.Tasks;
using K9Nano.Application;
using K9Nano.AspNetCore.Api;
using K9Nano.Authorization;
using K9Nano.IdentityServerCore.Roles.Dto;
using K9Nano.Share.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace K9Nano.IdentityServerCore.Roles
{
    [ApiController]
    [Route("role/[action]")]
    [Authorize]
    public class RoleController : CurdController<RoleCurdAppService, Authentication.Role, RoleCreateDto, RoleCreateDto, RoleItemDto,
        RolePagedInputDto, long>
    {
        private readonly IRbacManager _rbacManager;

        public RoleController(RoleCurdAppService curdAppService, IRbacManager rbacManager) : base(curdAppService)
        {
            _rbacManager = rbacManager;
        }

        [HttpGet]
        public override async Task<PagedResultDto<RoleItemDto>> List(RolePagedInputDto dto)
        {
            if (string.IsNullOrEmpty(dto.Api) || string.IsNullOrEmpty(dto.Resource))
            {
                return await base.List(dto);
            }

            var roles = await _rbacManager.GetRolesInResourceAsync(dto.Api, dto.Resource, HttpContext.RequestAborted);

            var result = await CurdAppService.ListAsync(roles.AsArray());

            return new PagedResultDto<RoleItemDto>(result.Count, result);
        }

        [HttpGet]
        public async Task<IReadOnlyList<IApiResource>> GetApiResources(string api, string role)
        {
            var result = await _rbacManager.GetResourcesInRolesAsync(api, new[] { role }, HttpContext.RequestAborted);
            return result;
        }

        [HttpPost]
        public async Task AddRoleToResources(EditRoleToResourcesDto input)
        {
            await _rbacManager.AddRoleToResourcesAsync(input.Api, input.Role, input.Resources,
                HttpContext.RequestAborted);
        }

        [HttpDelete]
        public async Task RemoveRoleFromResources(EditRoleToResourcesDto input)
        {
            await _rbacManager.RemoveRoleFromResourcesAsync(input.Api, input.Role, input.Resources,
                HttpContext.RequestAborted);
        }
    }
}